package org.myname.example1;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class Servlet2
 */
@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final String driver="com.mysql.jdbc.Driver";
	private final String url="jdbc:mysql://localhost:3306/web?useSSL=false";
	private final String u="root";
	private final String p="6775";

	private Connection conn = null;
	private String sql;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet2() {
        super();
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, u, p);
			System.out.println("Connect to database successfully!");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			String name =request.getParameter("name");
			String password=request.getParameter("password");
			sql="select * from user where name=? and password=? ";
			
			try {
				ps=conn.prepareStatement(sql);
				ps.setString(1, name);
				ps.setString(2, password);
				rs=ps.executeQuery();
				if(rs.next()){
					request.getSession().setAttribute("name", name);
					request.getSession().setAttribute("password", password);
					request.getSession().setAttribute("logged",new Integer(1));
					response.sendRedirect("Upload.jsp");
				}else{	
					throw  new  NullPointerException("null pointer");
				}						
			} catch (SQLException e) {
				e.printStackTrace();
				throw  new  NullPointerException("null pointer");
			}
				
			
		}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	

	

}
